package org.restql.db;

import java.util.Map;

public class WhereClauseGenerator {

	public static String generateWhereClause(Map queryMap, boolean multiTable) {
		String whereClause = "";
		String max = null;
		String skip = null;
		for (Object key : queryMap.keySet()) {
			// Limit amount of records
			if ( ((String) key).startsWith("rql:max") ) {
				max = ((String []) queryMap.get(key))[0];
			}
			// Skip forward through records
			else if ( ((String) key).startsWith("rql:skip") ) {
				skip = ((String []) queryMap.get(key))[0];
			}
			// Basic query param
			else {
				if (whereClause.length() == 0) whereClause = " WHERE ";
				if (whereClause.length() > 7) whereClause += " AND ";

				String val = ((String []) queryMap.get(key))[0];
				String operator = " = ";

				// Prefixes other than '='
				if (val.contains(":")) {
					String parts[] = val.split(":");
					val = parts[1];
					operator = mapToOp(parts[0]);
				}

				whereClause += key + operator + "'" + val + "'";
			}
		}

		if (max != null && skip != null) {
			whereClause += " LIMIT " + skip + "," + max;
		} else if (max != null && skip == null) {
			whereClause += " LIMIT " + max;
		}

		if (multiTable && whereClause.length() > 0) whereClause = " AND " + whereClause.substring(6);

		return whereClause;
	}

	protected static String mapToOp(String op) {
		if (op.equalsIgnoreCase("lt")) return " < ";
		else if (op.equals("lte")) return " <= ";
		else if (op.equals("gte")) return " >= ";
		else if (op.equals("gt")) return " > ";
		else if (op.equals("ne")) return " != ";
		else return " = ";
	}

}
